<?php
/*
 * @author lizhou
 * #date 2012/10/14
 * version 1.0
 */
class IndexAction extends Action {
	public function index() {
		//防止页面乱码  
		header ( "Content-Type:text/html; charset=utf-8" );
		if($_SESSION['user']) $this->redirect('Ucenter/index');
		$this->display();
	}
	
	// 登录
	public function login() {
		// 防止页面乱码  
		header ( "Content-Type:text/html; charset=utf-8" );
		if ($_POST['username']) {
			$username = $_POST['username'];
			$userpwd = md5 ( $_POST['password'] );
			$User = M ('Uinfo');
			// 判断登录用户名类型
			if(strstr($username,'@')) {
		 		$condition['email'] = $username;
		 		//$condition['veriEmail'] = '1';//邮箱验证功能未开通
		 		$condition['state'] = '1';
			} else if (preg_match('/^((13[0-9])|(15[0-9])|180|(18[5-9]))\d{8}$/',$username)) {		 		
		 		$condition['mobilePh'] = $username;
		 		//$condition['veriMobile'] = '1';//手机验证功能未开通
		 		$condition['state'] = '1';
		 	} else {
				$condition['username'] = $username;
				$condition['state'] = '1';
			}
			
			$result = $User->where ($condition)->find();
			if (! $result || $result ["password"] != $userpwd) {
				$this->ajaxReturn('','用户名或密码错误',0);   // ajax 用户名错误或者密码错误
			} else {
				setcookie(session_name(),session_id(),time()+1800,"/"); // 设置session生存期
				session('user',$result);
				if($result['userType']=='0') session('type','注册会员');
				else if($result['userType']=='1') session('type','VIP会员');
				else if($result['userType']=='2') session('type','专家认证会员');
				$data['lastLgTime'] = date('Y-m-d H:i:s',time());
				$User->where($condition)->save($data);
				// 记录用户日志
				$Log = M ('Userlog');
				$logData['userId'] = $result['userId'];
				$logData['transaction'] = '登录';
				$logData['logTime'] = $data['lastLgTime'];
				$Log->add($logData);
				
				//计算用户年龄（周岁）,保存到session
				$this->calculateAge();
				//转换用户性别
				if($result['gender']==0) session('usergender','男');
				else session('usergender','女');
				$this->ajaxReturn ('','',1);
			}
		}
		else $this->display();
	}
	
	// 首页快速评估
	public function estimate() {
		// 防止页面乱码  
		header ( "Content-Type:text/html; charset=utf-8" );
		$height = $_POST['height'];
		$weight = $_POST['weight'];
		$waistline = $_POST['waistline'];
		//快速评估参数性别默认男，默认成年人
		$data=$this->healthAssessment($height,$weight,$waistline,'男',20);
		$this->ajaxReturn($data,'',1);
    }
	
	// 生成验证码  
	public function verifyImage() {
		import ( "ORG.Util.Image" );
		Image::buildImageVerify ();
	}
	
	// 校验验证码
	public function checkCode() {
		// 防止页面乱码  
		header ( "Content-Type:text/html; charset=utf-8" );
		if (md5($_POST['value']) != $_SESSION['verify']) 
			$this->error();
		$this->success();
	}
	
	// 检查用户名是否可用
	public function checkUsername() {
		// 防止页面乱码  
		header ( "Content-Type:text/html; charset=utf-8" );
		$User = M ('Uinfo');
		$result = $User->getByUsername($_POST['value']);
		if(!$result) $this->success();
		else $this->error();
	}
	
	// 检查注册邮箱是否可用
	public function checkEmail() {
		// 防止页面乱码  
		header ( "Content-Type:text/html; charset=utf-8" );
		$User = M ('Uinfo');
		$result = $User->getByEmail($_POST['value']);
		if(!$result || $result['username']==$_SESSION['user']['username']) $this->success();
		else $this->error();
	}
	
	// 注册
	public function register() {
		// 防止页面乱码  
		header ( "Content-Type:text/html; charset=utf-8" );
		if($_SESSION['user']) {
			$this->redirect('Ucenter/index');
		} else if ($_POST['username']) {
			$userreg['username'] = $_POST['username'];
			$userreg['password'] = md5 ( $_POST['password'] );
			$userreg['usergender'] = $_POST['gender'];
			$userreg['birthday'] = $_POST['birthyear'].'-'.$_POST['birthmonth'].'-'.$_POST['birthday'];
			$userreg['email'] = $_POST['email'];
			$userreg['regTime'] = date('Y-m-d H:i:s',time());
			//头像按男女采用默认
			if($_POST['gender']) $userreg['headPic']="defaultf.jpg";
			else $userreg['headPic']="defaultm.jpg";
			

			$User = M ('Uinfo');
			//数据写入成功ajax
			if ($result=$User->add($userreg))
			{ 
				
				setcookie(session_name(),session_id(),time()+1800,"/"); // 设置session生存期
				$condition['username'] = $_POST['username'];
				$condition['state'] = '1';
				$result = $User->where ($condition)->find();
				session('user',$result);
				if($result['userType']=='0') session('type','注册会员');
				else if($result['userType']=='1') session('type','专家认证会员');
				else if($result['userType']=='2') session('type','VIP会员');
				// 记录用户日志
				$Log = M ('Userlog');
				$logData['userId'] = $result['userId'];
				$logData['transaction'] = '登录';
				$logData['logTime'] = $data['lastLgTime'];
				$Log->add($logData);
				
				//计算用户年龄（周岁）,保存到session
				$this->calculateAge();
				//转换用户性别
				if($result['gender']==0) session('usergender','男');
				else session('usergender','女');
				//新建用户文件夹
				$path="./Public/User/".$result['userId'];
				if(!file_exists($path)) mkdir($path,0777); 
				
				$this->ajaxReturn('','',1);
			}
			else $this->error();
			
		}
		//$this->display();
	}
	
	public function emailreg() {
		
	}
	
	public function emailveri() {
		
	}
	
	public function mobileveri() {
		
	}
	
	//计算用户年龄，调用session，保存到session，$_SESSION['userage']
	public function calculateAge() {
				$userbirth=explode('-',$_SESSION['user']['birthday']);
				$nowyear=date('Y',time());
				$ageflag=0;
				if ($userbirth[1]>date('m',time()))
				{
					$ageflag=-1;
				}
				elseif ($userbirth[1]==date('m',time())and$userbirth[2]>date('d',time()))
				{
					$ageflag=-1;
				}
				$userage=$nowyear-$userbirth[0]+$ageflag;
				session('userage',$userage);
	}
	
	//健康评估的功能函数，输入身高、体重、腰围、性别、年龄；输出数组包含：BMI、risk、suggestion
	public function healthAssessment($height,$weight,$waistline,$gender,$age) {
		if ($age>=0)//区分青少年和成人
    	{
   			$BMI=round($weight/$height/$height*10000,2);
        	if($gender=="男")
        	{
        		if($BMI<18.5)
        		{
        			$risk="正常";
        			$level=1;
        		}
        		elseif ($BMI>=18.5and$BMI<24)
        		{
        			if($waistline<85)
        			{
        				$risk="正常";
        				$level=2;
        			}
        			elseif($waistline>=85and$waistline<95)
        			{
        				$risk="增加";
        				$level=2;
        			}
        			else 
        			{
        				$risk="高";
        				$level=3;
        			}
        		}
        		elseif ($BMI>=24and$BMI<28)
        		{
        			if($waistline<85)
        			{
        				$risk="增加";
        				$level=4;
        			}
        			elseif($waistline>=85and$waistline<95)
        			{
        				$risk="高";
        				$level=4;
        			}
        			else 
        			{
        				$risk="极高";
        				$level=5;
        			}
        		}
        		else 
        		{
        			if($waistline<85)
        			{
        				$risk="高";
        				$level=6;
        			}
        			elseif($waistline>=85and$waistline<95)
        			{
        				$risk="极高";
        				$level=6;
        			}
        			else 
        			{
        				$risk="极高";
        				$level=6;
        			}
        		}
        	}
        	elseif ($gender=="女")
        	{
        	if($BMI<18.5)
        		{
        			$risk="正常";
        			$level=1;
        		}
        		elseif ($BMI>=18.5and$BMI<24)
        		{
        			if($waistline<80)
        			{
        				$risk="正常";
        				$level=2;
        			}
        			elseif($waistline>=80and$waistline<90)
        			{
        				$risk="增加";
        				$level=2;
        			}
        			else 
        			{
        				$risk="高";
        				$level=3;
        			}
        		}
        		elseif ($BMI>=24and$BMI<28)
        		{
        			if($waistline<80)
        			{
        				$risk="增加";
        				$level=4;
        			}
        			elseif($waistline>=80and$waistline<90)
        			{
        				$risk="高";
        				$level=4;
        			}
        			else 
        			{
        				$risk="极高";
        				$level=5;
        			}
        		}
        		else 
        		{
        			if($waistline<80)
        			{
        				$risk="高";
        				$level=6;
        			}
        			elseif($waistline>=80and$waistline<90)
        			{
        				$risk="极高";
        				$level=6;
        			}
        			else 
        			{
        				$risk="极高";
        				$level=6;
        			}
        		}
        	}
    	}
    	//不满18周岁的青少年
    	else
    	{
    	
    	}
    	switch ($level)
    	{
    		case 1:
    			$suggestion="增肌";
    			break;
    		case 2:
    			$suggestion="维持现有体重";
    			break;
    		case 3:
    			$suggestion="减腹部脂肪";
    			break;
    		case 4:
    			$suggestion="开始减肥";
    			break;
    		case 5:
    			$suggestion="减肥和减腹部脂肪";
    			break;
    		case 6:
    			$suggestion="减肥并筛查相关疾病";
    			break;
    		default:
    			break;
    	}
    	$data['bmi'] = $BMI;
    	$data['risk'] = $risk;
    	$data['advice'] = $suggestion;
    	$data['level'] = $level;
    	return $data;
	}
}
?>
